#include "ServerClient.h"
#include "Server.h"

#include <iostream>


ServerClient::ServerClient(void)
{

}

ServerClient::~ServerClient(void)
{
	WSACleanup();
}

bool ServerClient::listen() {
	try {
		char* buffer = new char[256];
		int i = recv( mySocket, buffer, 256, 0 );
		if(i == -1) {
			return false;
		} else if(buffer == "userList") {
			//SendData(server->getUserList());
		}
		else {
			buffer[i] = '\0';
			server->SendToAll(buffer);
			return true;
		}
		delete[] buffer;
	} catch(int e) {
		cout << "An exception occurred. Exception Nr. " << e << endl;
		return false;
	}
}

void ServerClient::setCallback(Server* s) {
	server = s;
}

void ServerClient::setName(string n) {
	name = n;
}

string ServerClient::getName() {
	return name;
}

void ServerClient::setSocket(SOCKET s) {
	mySocket = s;
}

void ServerClient::SendData(char* buffer) {
	send( mySocket, buffer, strlen( buffer ), 0 );
}

void ServerClient::run() {
	DWORD  m_dwThreadID;
	HANDLE m_hThread;
	m_hThread = CreateThread(0,0,ThreadFunc,this,0,&m_dwThreadID);
}

void ServerClient::disconnect() {
	server->disonnectClient((int)this);
}

unsigned long _stdcall ServerClient::ThreadFunc(void * param) {
	char recMessage[256];
	ServerClient* This = (ServerClient*)param;
	while(true) {
		bool b = This->listen();
		if(!b) {
			This->disconnect();
			break;
		}
	}
	return 0;
}

